from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse,HttpResponseRedirect
from .models import *
from django.views.generic import View
from django.conf import settings
# Create your views here.
from django.contrib.auth import authenticate, login, logout
from utils.Mixin import LoginRequiredMixin


class login_view(View):
    def get(self, request):
        if 'user_id' in request.COOKIES:
            user_id = request.COOKIES.get('user_id')
            password = request.COOKIES.get('password')
            checked = 'checked'
        else:
            user_id = ''
            password = ''
            checked = ''
        return render(request, 'login.html', {'user_id': user_id, 'password': password, 'checked':checked})
    def post(self, request):
        username = request.POST.get('user_id')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            next_url = request.GET.get('next', reverse('ITEM:index'))

            response = redirect(next_url)
            remember = request.POST.get('remember')
            if remember == 'on':
                response.set_cookie('user_id', username, max_age=10 * 24 * 3600)
                response.set_cookie('password', password, max_age=10 * 24 * 3600)
            else:
                response.delete_cookie('user_id')
            return response
        else:
            return render(request, 'login.html', {'errmsg':'用户名或密码错误', 'user_id': username, 'password':password})


class logout_view(LoginRequiredMixin,View):
    def get(self, request):
        logout(request)
        return redirect(reverse('ITEM:index'))

class reset_password_view(LoginRequiredMixin, View):
    def get(self, request, username):
        return render(request, 'shift.html')
    def post(self, request, username):
        #username = request.POST.get('username')
        #return HttpResponse(username)
        user = User.objects.get(username=username)
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        user = authenticate(username=username, password=old_password)
        if user:
            if len(new_password) <6:
                return render(request, 'shift.html', {'errmsg':'密码至少6位数', 'old_password':old_password, 'new_password':new_password})
            else:
                user.set_password(new_password)
                user.save()
        else:
            return render(request, 'shift.html',
                          {'errmsg': '原密码错误', 'old_password': old_password, 'new_password': new_password})
        #login(request, user)
        return render(request, 'index.html', {'message':'密码修改成功！'})
       # return redirect(reverse('ITEM:index', kwargs={'message':'密码修改成功！'}))